package com.fas.system.websocket;

import com.alibaba.fastjson.JSONObject;
import com.fas.system.service.ISysUserService;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class Pushing implements InitializingBean, DisposableBean {

    private static final Logger log = LoggerFactory.getLogger(Pushing.class);


    @Resource
    private PushService pushService;
    @Resource
    private Websocket websocket;
    @Resource
    private ISysUserService sysUserService;

    Thread thread;

    @Autowired
    public RedisTemplate<String, String> redisTemplate;

    boolean flag = true;

    @Override
    public void destroy() throws Exception {
        flag = false;
        log.info("线程销毁成功！！！！！！！！！！");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        thread = new Thread(() -> {
            while (flag) {
                String msg = pushService.readMsg();
                if (Strings.isNotBlank(msg)) {
                    sendMsg(msg);
                }
            }
        });
        thread.start();
    }

    private void sendMsg(String pushDataStr) {
        PushData pushData = JSONObject.parseObject(pushDataStr, PushData.class);
        websocket.sendMessage(pushDataStr,pushData.getUserList());
    }


}
